using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Vecen.BangChuang.BangChuang.Common;

namespace Vecen.BangChuang.BangChuang.DomainServices.Common
{
    public class CounterDomainService : BangChuangDomainServiceBase
    {
        private readonly IRepository<Counter, long> _counterRepository;

        public CounterDomainService(IRepository<Counter, long> counterRepository)
        {
            _counterRepository = counterRepository;
        }

        /// <summary>
        /// 记录
        /// </summary>
        /// <param name="counterType">类别</param>
        /// <param name="objectId">对象id</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public async Task RecordAsync(string counterType,int objectId, int count = 1)
        {
            await _counterRepository.InsertOrUpdateAndGetIdAsync(new Counter()
            {
                CounterType = counterType,
                ObjectId = objectId,
                Count = count
            });
        }

        /// <summary>
        /// 记录转发数量
        /// </summary>
        /// <param name="counterType"></param>
        /// <param name="objectId"></param>
        /// <param name="forwardedTarget"></param>
        /// <returns></returns>
        public async Task RecordForwardedAsync(string counterType, int objectId, string forwardedTarget) {
            await _counterRepository.InsertOrUpdateAndGetIdAsync(new Counter()
                {CounterType = counterType, ObjectId = objectId, Count = 1});
        }

        /// <summary>
        /// 获得指定计数类别的总计数量
        /// </summary>
        /// <param name="counterType"></param>
        /// <param name="objectId">统计对象</param>
        /// <returns></returns>
        public async Task<int> GetCountAsync(string counterType,int objectId) {
            return await _counterRepository.CountAsync(c => c.CounterType == counterType && c.ObjectId == objectId);
        }


        /// <summary>
        /// 取总数数量
        /// </summary>
        /// <param name="counterType"></param>
        /// <param name="objectId"></param>
        /// <returns></returns>
        public Task<int> GetSumCountAsync(string counterType, int? objectId)
        {
            var query = _counterRepository.GetAll().Where(c => c.CounterType == counterType)
                .WhereIf(objectId.HasValue, c => c.ObjectId == objectId);

            return Task.Run(() =>
            {
                return query.Sum(c => c.Count);
            });
        }
    }
}